package com.bjpowernode.crm.advice;

import com.bjpowernode.crm.constants.Constants;
import com.bjpowernode.crm.pojo.User;
import com.bjpowernode.crm.utils.UUIDUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class EditAdvice implements Advice {

    @Autowired(required=false)
    private HttpSession session;

    @Around("execution(* *..service..*.edit*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        Object result = null;

        Object[] args = pjp.getArgs(); // 方法的参数
        try {
            Object o = args[0]; // 要添加的实体
            User user = (User) session.getAttribute(Constants.LOGIN_USER);
            String editBy = user.getLoginAct() + "|" + user.getName();
            String editTime = Constants.DateFormat.SDF19.format(new Date());

            // 使用反射为对象中的属性赋值
            Class clazz = o.getClass();

            // 通过set方法赋值
            try {
                Method setEditBy = clazz.getMethod("setEditBy", String.class);
                setEditBy.invoke(o, editBy);
            } catch (Exception e) {
            }
            try {
                Method setEditTime = clazz.getMethod("setEditTime", String.class);
                setEditTime.invoke(o, editTime);
            } catch (Exception e) {
            }
            try {
                Method setEditBy = clazz.getMethod("setEditPerson", String.class);
                setEditBy.invoke(o, editBy);
            } catch (Exception e) {
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }

        result = pjp.proceed(); // 调用目标方法
        return result;
    }
}
